<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 4] 4.4 Unary Operators</TITLE>
<META NAME="author" CONTENT="Mark Grand">
<META NAME="date" CONTENT="Thu Jul 31 13:10:04 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="java">
<META NAME="title" CONTENT="Java Language Reference">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java Language Reference" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch04_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 4<br>Expressions</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch04_05.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4">4.4 Unary Operators</A></h2>

<P CLASS=para>
<A NAME="CH04.UNARY1"></A><A NAME="CH04.UNARY2"></A>Unary operators are operators that take exactly one argument. Unary
operators may appear in a unary expression:


<p>
<img align=middle src="./figs/jlr0414.gif" alt="[Graphic: Figure from the text]" width=425 height=100 border=0>

<P CLASS=para>
The unary plus and minus operators, a Boolean negation operator
(<tt CLASS=literal>!</tt>),
a bitwise negation operator (<tt CLASS=literal>~</tt>), and the cast
construct comprise the unary operators in Java. The unary operators
are equal in precedence and are evaluated from right to left.

<P CLASS=para>
<b>References</b>
<A HREF="ch04_14.htm#JLR2-CH-4-SECT-14">Order of Operations</A>;
<A HREF="ch04_03.htm#JLR2-CH-4-SECT-3.1">Postfix Increment/Decrement Operators</A>;
<A HREF="ch04_03.htm#JLR2-CH-4-SECT-3.2">Prefix Increment/Decrement Operators</A>;
<A HREF="ch04_01.htm#JLR2-CH-4-SECT-1">Primary Expressions</A>;
<I CLASS=emphasis>Type</I> 3

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4.1">Unary Plus Operator +</A></h3>

<P CLASS=para>
The unary plus operator (<tt CLASS=literal>+</tt>)
can appear as part of a unary expression. The operator does no explicit
computation; it produces the same pure value that is produced by
its operand. However, the unary + operator may perform a type conversion
on its operand. The type of the operand must be an arithmetic data
type, or a compile-time error occurs. If the type of the operand
is <tt CLASS=literal>byte</tt>, <tt CLASS=literal>short</tt>, or <tt CLASS=literal>char,</tt>
the unary <tt CLASS=literal>+</tt> operator produces an <tt CLASS=literal>int</tt>
value; otherwise the operator produces a value of the same type
as its operand.

<P CLASS=para>
<b>References</b>
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.1">Arithmetic Types</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4.2">Unary Minus Operator -</A></h3>

<P CLASS=para>
The unary minus
operator (<tt CLASS=literal>-</tt>)
can appear as part of a unary expression. The type of the operand
of the unary <tt CLASS=literal>-</tt> operator must be an arithmetic
data type, or a compile-time error occurs. The operator produces
a pure value that is the arithmetic negation (i.e., additive inverse)
of the value of its operand.

<P CLASS=para>
The unary <tt CLASS=literal>-</tt>
operator may perform a type conversion. If the type of the operand
is <tt CLASS=literal>byte</tt>, <tt CLASS=literal>short</tt>, or <tt CLASS=literal>char</tt>,
the operation converts the operand to an <tt CLASS=literal>int</tt>
before computing the value's arithmetic negation and producing an
<tt CLASS=literal>int</tt> value. Otherwise, unary <tt CLASS=literal>-</tt>
produces a value of the same type as its operand.

<P CLASS=para>
For integer data types, the unary <tt CLASS=literal>-</tt> operator produces
a value equivalent to subtracting its operand from zero.
There are, however, negative values for which the unary <tt CLASS=literal>-</tt> operator
cannot produce a positive value; in these cases it produces the
same negative value as its operand. This behavior results from the
two's complement representation Java uses for integer values. The
magnitude of the most negative number that can be represented using
two's complement notation cannot be represented as a positive number.
No exception is thrown when the unary <tt CLASS=literal>-</tt> operator
is given a value that cannot be negated. However, you can detect
this situation by explicitly testing for these special values. The
most negative <tt CLASS=literal>int</tt> value is available as the predefined
constant <tt CLASS=literal>Integer.MIN_VALUE</tt> and the most negative
<tt CLASS=literal>long</tt> value is available as the predefined constant
<tt CLASS=literal>Long.MIN_VALUE</tt>.

<P CLASS=para>
For floating-point
data types, the unary <tt CLASS=literal>-</tt> operator changes the
sign of its operand from <tt CLASS=literal>+</tt> to <tt CLASS=literal>-</tt>
or from <tt CLASS=literal>-</tt> to <tt CLASS=literal>+</tt>, for both regular
values, positive and negative zero, and positive and negative infinity.
The only case where this is not true occurs when the operand is
not-a-number (NaN).
Given the value NaN, the unary <tt CLASS=literal>-</tt> operator produces
NaN.

<P CLASS=para>
<b>References</b>
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.1">Arithmetic Types</A>;
<A HREF="ch10_10.htm">Integer</A>;
<A HREF="ch10_11.htm">Long</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4.3">Boolean Negation Operator !</A></h3>

<P CLASS=para>
The Boolean negation operator (<tt CLASS=literal>!</tt>)
may appear as part of a unary expression. The type of the operand
of the <tt CLASS=literal>!</tt> operator must be <tt CLASS=literal>boolean</tt>,
or a compile-time error occurs. If the value of its operand is <tt CLASS=literal>false</tt>,
the <tt CLASS=literal>!</tt> operator produces the pure <tt CLASS=literal>boolean</tt>
value <tt CLASS=literal>true</tt>. If the value of its operand is <tt CLASS=literal>true</tt>,
the operator produces the pure <tt CLASS=literal>boolean</tt> value
<tt CLASS=literal>false</tt>.

<P CLASS=para>
Here is an example that uses
the Boolean negation operator:

<DIV CLASS=screen>
<P>
<PRE>
public void paint(Graphics g) {
    if (!loaded) {
        //The next 2 lines are executed if loaded is false
        g.drawString("Loading data", 25, 25);
        return;
    }
    g.drawImage(img, 25, 25, this);
}
</PRE>
</DIV>

<P CLASS=para>
<b>References</b>
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.2">Boolean Type</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4.4">Bitwise Negation Operator ~</A></h3>

<P CLASS=para>
The bitwise negation operator (<tt CLASS=literal>~</tt>)
may appear as part of a unary expression. The type of the operand
of the <tt CLASS=literal>~</tt> operator must be an integer data type,
or a compile-time error occurs. The <tt CLASS=literal>~</tt> operator
may perform a type conversion before it performs its computation.
If the type of the operand is <tt CLASS=literal>byte</tt>, <tt CLASS=literal>short</tt>,
or <tt CLASS=literal>char</tt>, the operator converts its operand to
<tt CLASS=literal>int</tt> before producing a value. Otherwise the <tt CLASS=literal>~</tt>
operator produces a value of the same type as its operand.

<P CLASS=para>
After
type conversion, the bitwise negation operator produces a pure value
that is the bitwise complement of its operand. In other words, if
a bit in the converted operand contains a one, the corresponding
bit in the result contains a zero. If a bit in the converted operand
contains a zero, the corresponding bit in the result contains a
one.

<P CLASS=para>
Here's an example that shows the use of the bitwise
negation operator:

<DIV CLASS=screen>
<P>
<PRE>
// zero low order four bits
int getNibble(int x) {
    return x &amp; ~0xf;
}
</PRE>
</DIV>

<P CLASS=para>
<b>References</b>
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.1.1">Integer types</A>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JLR2-CH-4-SECT-4.5">Casts</A></h3>

<P CLASS=para>
<A NAME="CH04.CAST1"></A><A NAME="CH04.CAST2"></A><A NAME="CH04.CAST3"></A>A <I CLASS=emphasis>Type</I> enclosed
in parentheses specifies a type cast operation.
A cast may appear as part of a unary expression. A cast operation
always produces a pure value of the specified type, by converting
its operand to that type if necessary. This is different from a
type cast in C/C++, which can produce garbage if it is given a pointer
to a data type different than that implied by the pointer's declaration.
If the actual data type of the operand of a cast cannot be guaranteed
at compile-time, the Java compiler must produce code to check the
type of the operand at runtime. In Java, any value that gets past
all of the type-checking done on a cast is guaranteed to be compatible
with the type specified by the cast.

<P CLASS=para>
A cast can convert
between certain primitive types. A cast between object reference
types never alters the type or content of the object, but may alter
the type of the reference to the object.

<P CLASS=para>
Because it
is not possible to convert between all types, some cast operations
are permitted and others are not. Here are the rules governing casts:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>A value of any data type can be cast to its own type.

<P>
<li CLASS=listitem>A value of any arithmetic data type can be cast to any other
arithmetic data type. Casting a floating-point value to an integer
data type rounds toward zero.

<P>
<li CLASS=listitem>A value of the <tt CLASS=literal>boolean</tt> data type cannot be cast to
any other data type, nor can
a value of any other data type be cast to <tt CLASS=literal>boolean</tt>.

<P>
<li CLASS=listitem>A value of any primitive data type cannot be cast to a reference
data type, nor can a reference be cast to any primitive data type.

<P>
<li CLASS=listitem>A reference to a class type can be cast to the type of the
superclass of that class.

<P>
<li CLASS=listitem>A reference to a class type can be cast to the type of a subclass
of that class if the reference actually refers to an object of the
specified class or any of its subclasses. Unless the Java compiler
can prove that the object actually referenced is of the specified
class or any of its subclasses, the compiler must generate a runtime
test to verify that the object is of an appropriate type. At runtime,
if the object actually referenced is not of an appropriate type,
a <tt CLASS=literal>ClassCastException</tt> is thrown. Consider the
following example:

<DIV CLASS=screen>
<P>
<PRE>
Object o = "ABC";
String s = (String)o;   // This is okay
Double d = (Double)o;   // Throws an exception
</PRE>
</DIV>

<P CLASS=para>
The cast of <tt CLASS=literal>o</tt> to <tt CLASS=literal>String</tt>
is fine because <tt CLASS=literal>o</tt> is really a reference to a <tt CLASS=literal>String</tt> object. The cast of <tt CLASS=literal>o</tt> to
<tt CLASS=literal>Double</tt> throws an exception at runtime because
the object that <tt CLASS=literal>o</tt> references is not an instance
of <tt CLASS=literal>Double</tt>.

<P>
<li CLASS=listitem>A reference to a class type can be cast to an interface type
if the reference actually refers to an object of a class that implements
the specified interface. If the class of the reference being cast
is a <tt CLASS=literal>final</tt> class, the compiler can determine
if the reference actually refers to an object of a class that implements
the specified interface, because a <tt CLASS=literal>final</tt> class
cannot have any subclasses. Otherwise, the compiler must generate
a runtime test to determine if the reference actually refers to
an object of a class that implements the specified interface. At
runtime, if the object actually referenced is not of a class that
implements the interface, a <tt CLASS=literal>ClassCastException</tt> is
thrown. Here is an example that illustrates the rules governing casts to
interface types:

<DIV CLASS=screen>
<P>
<PRE>
interface Weber { double flux(double x); }
class B {}
final class C {}
class D implements Weber {
    public double flux(double x) {
        return Math.PI*x*x;
    }
}
class Intercast {
    public void main(String[] argv) {
        B b = new B();
        C c = new C();
        D d = new D();
        Weber w;
        w = (Weber)b;   // Throws an exception
        w = (Weber)c;   // Compiler complains
        w = (Weber)d;   // Okay, D implements Weber
    }
}
</PRE>
</DIV>

<P CLASS=para>
The cast of <tt CLASS=literal>b</tt> to <tt CLASS=literal>Weber</tt>
is fine with the compiler because the class <tt CLASS=literal>B</tt>
might have a subclass that implements <tt CLASS=literal>Weber</tt>.
At runtime, however, this cast throws an exception because <tt CLASS=literal>B</tt>
does not implement <tt CLASS=literal>Weber</tt>. The cast of <tt CLASS=literal>c</tt>
to <tt CLASS=literal>Weber</tt> produces an error message from the compiler,
as the <tt CLASS=literal>C</tt> class does not implement <tt CLASS=literal>Weber</tt>.
Because <tt CLASS=literal>C</tt> is <tt CLASS=literal>final</tt>, it will
not have any subclasses and therefore there is no possibility of
<tt CLASS=literal>c</tt> containing a reference to an object that implements
the <tt CLASS=literal>Weber</tt> interface. The cast of <tt CLASS=literal>d</tt>
to <tt CLASS=literal>Weber</tt> is fine because the <tt CLASS=literal>D</tt>
class implements the <tt CLASS=literal>Weber</tt> interface.

<P>
<li CLASS=listitem>A reference to the class <tt CLASS=literal>Object</tt> can be cast to
an array type if the reference actually refers to an array object
of the specified type. The compiler generates a runtime test to
determine if the reference actually refers to the specified type
of array object. At runtime, if the object actually referenced is
not the specified type of array, a <tt CLASS=literal>ClassCastException</tt>
is thrown.

<P>
<li CLASS=listitem>A reference to an interface type can be cast
to a class type if the reference actually refers to an instance
of the specified class or any of its subclasses. If the specified
class is a <tt CLASS=literal>final</tt> class that does not implement
the referenced interface, the compiler can reject the cast because
a <tt CLASS=literal>final</tt> class cannot have any subclasses. Otherwise,
the compiler generates a runtime test to determine if the reference
actually refers to an object of the appropriate type. At runtime,
if the object actually referenced is not of the appropriate type,
a <tt CLASS=literal>ClassCastException</tt> is thrown.

<P CLASS=para>
Here is an example to illustrate these points:

<DIV CLASS=screen>
<P>
<PRE>
interface Weber { double flux(double x); }
class B {}
final class C {}
class D implements Weber {
    public double flux(double x) {
        return Math.PI*x*x;
    }
}
class Intercast {
    public void doit(Weber w) {
        B b = (B)w;   // May throw an exception
        C c = (C)w;   // Compiler complains
        D d = (D)w;   // Okay
    }
}
</PRE>
</DIV>

<P CLASS=para>
The cast of <tt CLASS=literal>w</tt> to class <tt CLASS=literal>B</tt>
is fine with the compiler even though <tt CLASS=literal>B</tt> does
not implement <tt CLASS=literal>Weber</tt>. The compiler lets it pass
because <tt CLASS=literal>B</tt> might have a subclass that implements
<tt CLASS=literal>Weber</tt> and <tt CLASS=literal>w</tt> could contain
a reference to that class. However, at runtime, the cast will throw
an exception if the object actually referenced is not an instance
of <tt CLASS=literal>B</tt> or a subclass of <tt CLASS=literal>B</tt>. The
cast of <tt CLASS=literal>w</tt> to class <tt CLASS=literal>C</tt> produces
an error message from the compiler. <tt CLASS=literal>C</tt> does not
implement <tt CLASS=literal>Weber</tt> and <tt CLASS=literal>C</tt>
cannot have any subclasses
because it is <tt CLASS=literal>final</tt>; any object
that implements <tt CLASS=literal>Weber</tt> cannot be an instance of
<tt CLASS=literal>C</tt>. The cast of <tt CLASS=literal>w</tt> to class
<tt CLASS=literal>D</tt> is fine at compile-time because <tt CLASS=literal>D</tt>
implements <tt CLASS=literal>Weber</tt>. At runtime, if 
<tt CLASS=literal>w</tt> references an object that is
not an instance of <tt CLASS=literal>D</tt>, a 
<tt CLASS=literal>ClassCastException</tt> is thrown.

<P>
<li CLASS=listitem>A reference to an interface type can be cast to another interface
type if the reference actually refers to an object of a class that
implements the specified interface. If the referenced interface extends
the specified interface, the compiler knows that the cast is legal.
Otherwise, the compiler generates a runtime test to determine if
the reference actually refers to an object that implements the specified
interface. At runtime, if the object actually referenced does not
implement the specified interface, a <tt CLASS=literal>ClassCastException</tt>
is thrown.

<P CLASS=para>
Here is an example to illustrate these points:

<DIV CLASS=screen>
<P>
<PRE>
interface Weber { double flux(double x); }
interface Dyn { double squeeze(); }
interface Press extends Dyn {
    double squeeze(double theta);
}
class D implements Press {
    public double squeeze() { return Math.PI; }
    public double squeeze(double theta) {
        return Math.PI*Math.sin(theta);
    }
}
class Interinter {
    public static void doit(D d) {
        Dyn dyn = d;          // Okay
        Weber w = (Weber)d;   // May throw exception
    }
}
</PRE>
</DIV>

<P CLASS=para>
The assignment of <tt CLASS=literal>d</tt> to <tt CLASS=literal>dyn</tt>
works because <tt CLASS=literal>d</tt> is of class <tt CLASS=literal>D</tt>,
<tt CLASS=literal>D</tt> implements <tt CLASS=literal>Press</tt>, and <tt CLASS=literal>Press</tt>
extends <tt CLASS=literal>Dyn</tt>. Therefore, <tt CLASS=literal>d</tt>
refers to an object that implements <tt CLASS=literal>Dyn</tt> and we
have assignment compatibility. The compiler lets the cast of <tt CLASS=literal>d</tt>
to <tt CLASS=literal>Weber</tt> pass because there may be a subclass
of <tt CLASS=literal>D</tt> that implements <tt CLASS=literal>Weber</tt>.
At runtime, the cast will throw an exception if <tt CLASS=literal>D</tt>
does not implement <tt CLASS=literal>Weber</tt>.

<P>
<li CLASS=listitem>A reference
to an array object can be cast to the class type <tt CLASS=literal>Object</tt>.

<P>
<li CLASS=listitem>A reference to an array object can be cast to another array
type if either of the following is true:
<P>
<UL CLASS=itemizedlist>
<li CLASS=listitem>The elements
of the referenced array and the elements of the specified array
type are of the same primitive type.

<P>
<li CLASS=listitem>The elements of
the referenced array are of a type that can be cast to the type
of the elements of the specified array type.

<P>
</UL>
<P>
</UL>
<P CLASS=para>
Any cast operation not covered by the preceding rules is not
allowed and the Java compiler issues an error message.

<P CLASS=para>
<b>References</b>
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.1">Arithmetic Types</A>;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.3">Array Types</A>;
<A HREF="ch03_01.htm#JLR2-CH-3-SECT-1.2">Boolean Type</A>;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.1">Class Types</A>;
<A HREF="ch03_02.htm#JLR2-CH-3-SECT-2.2">Interface Types</A>;
<A HREF="ch09_04.htm#JLR2-CH-9-SECT-4.1.1">Runtime exceptions</A>

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch04_03.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch04_05.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Increment/Decrement Operators</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Multiplicative Operators</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
